package com.example.spring.security.utils.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;


import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by chijr on 17/3/10.
 */

/**
 * @author fanglj
 *
 */
@Slf4j
public class HttpUtils {

  static OkHttpClient getOkHttpClient(){
  	OkHttpClient okHttpClient = new OkHttpClient.Builder()
        .connectTimeout(300, TimeUnit.SECONDS)
        .writeTimeout(300, TimeUnit.SECONDS)
        .readTimeout(300, TimeUnit.SECONDS)
        .build();
  	return okHttpClient;
  }
  
  static public String get(String url){
     return requestGet(url,null,null,null);
  }
  /**
   *
   * 发送get请求
   * @param url 请求地址
   * @param coding 编码格式
   * @return:java.lang.String
   * @since: 1.0.0
   * @Author:hezeyu
   * @Date: 2021/5/8 10:17
   */
  static public String get(String url,String coding){
      return requestGet(url,null,null,coding);
  }
  static public String requestGet(String url, Map<String, String> params, Map<String,String> heads,String coding){
    OkHttpClient okHttpClient = getOkHttpClient();
    Request.Builder reqBuild = new Request.Builder();
    HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
    if (params != null) {
      for (String key : params.keySet()) {
      	String value= params.get(key);
      	if(StringUtils.isNotEmpty(value)){
      		 urlBuilder.addQueryParameter(key, value);
      	}
      	
      }
    }
    reqBuild.url(urlBuilder.build());
    if (heads != null) {
      for (String key : heads.keySet()) {
      	String value= heads.get(key);
      	if(StringUtils.isNotEmpty(value)){
      		 reqBuild.addHeader(key, value);
      	}
      	
      }
    }
    Request req = reqBuild.build();
    try {
      Response response = okHttpClient.newCall(req).execute();
      String str=null;

     if(response.isSuccessful()){
         if(coding!=null){
             byte[] b =response.body().bytes();
             str = new String(b, coding);
         }else{
             str=response.body().string();
         }
         return str;
     }
    } catch (IOException e) {
    	log.error("调用url={}异常::{}",url, JSONObject.toJSONString(e));
      throw new RuntimeException(e);
    }
    return null;
  }

  static public String requestPostBody(String url, String json, Map<String,String> heads) {//throws EWalletException{
    OkHttpClient okHttpClient = getOkHttpClient();
    MediaType JSONType = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSONType, json);
    Request.Builder builder = new Request.Builder();
    builder.url(url);
    if (heads != null) {
      for (String key : heads.keySet()) {
      	String value= heads.get(key);
      	if(StringUtils.isNotEmpty(value)){
      		 builder.addHeader(key,value );
      	}
      }
    }
    builder.post(body);
    Request req = builder.build();
    try {
      log.info("###########调用地址{} 调用参数:{}",url,json);
      Response response = okHttpClient.newCall(req).execute();
      String str=response.body().string();
      if(response.code()==200){
     	 log.info("###########调用地址{} 服务调用成功！",url);
      }else{
     	 log.error("@@@@@@@@@@@返回信息:{}",str);
      }
      return str;
    } catch (IOException e) {
    	log.error("调用url={}异常::{}",url, JSONObject.toJSONString(e));
    	throw new RuntimeException(e);
    }

  }

  static public String requestPostForm(String url, Map<String, String> params, Map<String,String> heads) {
  	OkHttpClient okHttpClient = getOkHttpClient();
    Request.Builder builder = new Request.Builder();

    builder.url(url);
    FormBody.Builder bodyBuilder = new FormBody.Builder();
    if (params != null) {
      for (String key : params.keySet()) {
      	String value= params.get(key);
      	if(StringUtils.isNotEmpty(value)){
      		 bodyBuilder.add(key,value);
      	}
        
      }
    }
    RequestBody body = bodyBuilder.build();
    if (heads != null) {
      for (String key : heads.keySet()) {
      	String value= heads.get(key);
      	if(StringUtils.isNotEmpty(value)){
      		 builder.addHeader(key,value );
      	}
        
      }
    }
    builder.url(url);
    builder.post(body);
    Request req = builder.build();
    try {
      log.info("###########调用地址{} 调用参数 {}",url, JSON.toJSONString(params));
      Response response = okHttpClient.newCall(req).execute();
      String str=response.body().string();
      if(response.code()==200){
       log.info("###########调用地址{} 服务调用成功！",url);
      }else{
      	log.error("@@@@@@@@@@@返回信息:{}",str);
      }
      return str;
    } catch (IOException e) {
    	log.error("调用url={}异常::{}::参数{}",url, JSONObject.toJSONString(e));
    	throw new RuntimeException(e);
    }
  }
  

  /**于是可得出获得客户端真实IP地址的方法一
   * @param request
   * @return
   *//*
  public static String getRemortIP(HttpServletRequest request) {
    if (request.getHeader("x-forwarded-for") == null) {
      return request.getRemoteAddr(); 
    } 
    return request.getHeader("x-forwarded-for"); 
  } 

  *//** 在公网服务器上，抓公网的ip
   * 获取当前公网ip 
   * @param request 
   * @return 
   *//*
  public static String getIpAddr(HttpServletRequest request){
      String ipAddress1 = request.getHeader("x-forwarded-for"); 
      String ipAddress2 = request.getHeader("Proxy-Client-IP"); 
      String ipAddress3 =  request.getHeader("WL-Proxy-Client-IP"); 
      String ipAddress4 =  request.getRemoteAddr();  
      
      logger.info("x-forwarded-for ip={}",ipAddress1);
      logger.info("Proxy-Client-IP ip={}",ipAddress2);
      logger.info("WL-Proxy-Client-IP ip={}",ipAddress3);
      logger.info("getRemoteAddr ip={}",ipAddress4);

      String ipAddress=ipAddress1;
      if(ipAddress ==null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { 
        ipAddress =ipAddress2; 
      } 
      if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { 
        ipAddress = ipAddress3;
      } 
      if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) { 
        ipAddress = ipAddress4;
      }
      
      //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割 
      if(ipAddress!=null && ipAddress.length()>15){//"***.***.***.***".length() = 15 
        if(ipAddress.indexOf(",")>0){
          ipAddress = ipAddress.substring(0,ipAddress.indexOf(",")); 
        } 
      }
      logger.info("最终得到客户端 ip={}",ipAddress);
      return ipAddress;  
  } 
*/
}
